/*
 * iShopPlace Project.
 */
package ishopplace.view.bean;

import ishopplace.model.businessobject.*;
import ishopplace.model.exception.iShopPlaceException;
import ishopplace.view.util.FacesUtils;

import javax.faces.FacesException;

import org.springframework.beans.support.PagedListHolder;


/**
 * Product page backing bean for the view product page.
 * 
 * @author <a href="mailto:derek@derekshen.com">Derek Y. Shen</a>
 */
public class ProductPageBean extends BasePaginationBean {
	private String productId;
	private String productName;
	
	public ProductPageBean() {
		super();
		this.logger.debug("ProductPageBean is created");
	}
	
	/**
	 * Initializes ProductPageBean.
	 * 
	 * @see BaseBean#init()
	 */
	protected void init() {
		this.logger.debug("init() is invoked");
		this.logger.debug("productId = " + this.productId);
		this.logger.debug("page = " + this.getPage());
		
		Product product = null;
		if (this.productId != null) {
			try {
				product = this.getServiceLocator().getCatalogService().getProduct(productId);
				this.productName = product.getName();
				this.setPagedListHolder(new PagedListHolder(
					this.getServiceLocator().getCatalogService().getItemListByProduct(this.productId)));
			} catch (iShopPlaceException me) {
				String msg = "Could not retrieve item list for product id of " + this.productId;
				this.logger.error(msg, me);
				throw new FacesException(msg, me);
			}
			
			//put in the session
			FacesUtils.getSessionBean().setCurrentProduct(product);
			FacesUtils.getSessionBean().setCurrentItemList(this.pagedListHolder);
		}
		else {
			product = (Product)FacesUtils.getSessionBean().getCurrentProduct();
			this.productName = product.getName();
			this.pagedListHolder = FacesUtils.getSessionBean().getCurrentItemList();
			
			if (product == null || this.pagedListHolder == null) {
				String msg = "Could not find product or item list in session";
				this.logger.error(msg);
				throw new FacesException(msg);
			}
			this.nagivate();
		}
		this.logger.debug("ProductPageBean is initialized");
	}
	
	public void setProductId(String newProductId) {
		this.productId = newProductId;
	}
	
	public String getProductName() {
	    return this.productName;
	}
}